package mya_dc.master_server.threads;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import mya_dc.master_server.MasterServerGUI;
import mya_dc.master_server.database.ClientsHashTable;
import mya_dc.master_server.database.ServersHashTable;

/**
 * a Thread manager for new client-threads
 *
 * @author      Adam Levi
 * @author		Yuval Shimron
 * <br>			MYA
 */
public class ClientsManager extends MYA_ThreadManager implements Runnable
{
	/**
	 * Constructor
	 * 
	 * @param ParentGUI - The parent's GUI
	 * @param clientsArray - The client's Hash-Table
	 * @param compilationServers - The Server's Hash-Table
	 * @param serverSocket - The server's socket
	 */
	public ClientsManager(
			MasterServerGUI ParentGUI,
			ClientsHashTable clientsArray,
			ServersHashTable compilationServers,
			ServerSocket serverSocket
			)
	{
		m_ParentGUI = ParentGUI;
		m_ServerSocket = serverSocket;
		m_ClientsArray = clientsArray;
		m_CompilationServers = compilationServers;
	
	}
	
	@Override
	public void run()
	{
		acceptNewClients();
		try 
		{
			m_ServerSocket.close();
		}
		catch (IOException e)
		{
			//error - closing server
		}
	}
	
	private MasterServerGUI 			m_ParentGUI;
	private ServerSocket 				m_ServerSocket;
	private ServersHashTable 			m_CompilationServers;
	ClientsHashTable					m_ClientsArray;

	private void acceptNewClients()
	{
		while(true)
		{
			try
			{
				Socket newClientSocket = m_ServerSocket.accept();
				ClientListenerThread tmp = new ClientListenerThread(
						m_ParentGUI,
						m_ClientsArray,
						m_CompilationServers,
						newClientSocket);
				m_Theards.add(tmp);
				new Thread(tmp).start();
			} 
			catch (IOException e)
			{
				try { m_ServerSocket.close(); }
				catch (IOException e1) { }
				doClose(); //closing clients
				break;
			}
			
		}
	}
}
